package com.itheima.health.service.impl;

import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author spt
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public User findByUsername(String username) {
        //先查基本信息
        User user = userDao.selectByUsername(username);
        if (null == user) {
            //用户不存在
            return null;
        }
        return user;
    }

    /**
     * 获取当前登录的用户的权限
     *
     * @param username
     * @return
     */
    @Override
    public List<String> findPermissions(String username) {
        //查询user表
        User user = userDao.selectByUsername(username);
        Integer userId = user.getId();
        //查询UserRole关联表，看此用户对应什么角色
        List<Integer> roleIds = userDao.selectUserRole(userId);

        Set<Integer> permissionIds=new HashSet<>();
        for (Integer roleId : roleIds) {
            //查询角色权限关联表
            permissionIds= userDao.selectPermissionsId(roleId);
        }

        //查询权限表
        List<String> permissionsLis = new ArrayList<>();
        for (Integer integer : permissionIds) {
            String name=userDao.selectPermissions(integer);
            //添加到集合中
            permissionsLis.add(name);
        }


        return permissionsLis;
    }
}
